#!/usr/bin/bash
#
# Copyright 2012-2018 the Pacemaker project contributors
#
# The version control history for this file may have further details.
#
# This source code is licensed under the GNU General Public License version 2
# or later (GPLv2+) WITHOUT ANY WARRANTY.
#

start="$PWD"
test_home=$(dirname "$0")
test_dir="/usr/share/pacemaker/tests"

if [ "$test_home" != "$test_dir" ]; then
    # Running against the source tree
    GCOV_BASE="/root/rpmbuild/BUILD/pacemaker-744a30d655c9fbd66ad6e103697db0283bb90779"
    test_dir="/root/rpmbuild/BUILD/pacemaker-744a30d655c9fbd66ad6e103697db0283bb90779/cts"
    cd "/root/rpmbuild/BUILD/pacemaker-744a30d655c9fbd66ad6e103697db0283bb90779" || exit 1
    
    grep with-gcov config.log
    if [ $? -eq 0 ]; then
	echo "Pacemaker was built with gcov support"
    else
	echo "Re-building with gcov support"
	last=`grep --color=never "$.*configure" config.log | tail -n 1 | sed s:.*configure:./configure: | sed s:--no-create:--with-gcov:`
	eval $last
    fi
    
    #sudo make core core-install

else
    GCOV_BASE=/var/lib/pacemaker/gcov/
    mkdir -p $GCOV_BASE

    export GCOV_PREFIX_STRIP=4
    export GCOV_PREFIX=$GCOV_BASE

    top=`find / -name crm_internal.h 2>/dev/null | grep debug | head -n 1`
    if [ "x$top" = x ]; then
	echo "Could not locate the pacemaker headers"
	exit 1
    fi

    cd "$(dirname "$top")" || exit 1
    cd .. || exit 1

    echo "Creating the directory structure in $GCOV_BASE from $PWD"
    # The .gcno files will already be there for sources,
    # but we still need to create the include/ subtree
    find . -type d -exec mkdir -p $GCOV_BASE/\{\} \;

    echo "Now linking the source files into place"
    find . -type f -name "*.c" -exec ln -s $PWD/\{\} $GCOV_BASE\{\} \;
    find . -type f -name "*.h" -exec ln -s $PWD/\{\} $GCOV_BASE\{\} \;
    find . -type f -name "*.debug" -exec ln -s $PWD/\{\} $GCOV_BASE\{\} \;
fi

cd "$start" || exit 1
lcov -d $GCOV_BASE -z

# Run all active regression tests
$test_dir/cts-regression

lcov -d $GCOV_BASE -c -o pacemaker.info

rm -rf html
mkdir html
genhtml -o html pacemaker.info
 
